<?php

function _buildQuery($data)
{
    $str = '';
    if(is_array($data)){
        foreach ($data as $key => $value) {
            if(is_array($value)) {
                $str .= $key.'='.json_encode($value,JSON_UNESCAPED_UNICODE).'&';
            }else {
                $str .= $key.'='.$value.'&';
            }
        }
        $str = mb_substr($str,0,-1);
    }else {
        $str = $data;
    }
    return $str;
}

// 1.登录
// $str = '{"mobile":"15386439173","password":"123456"}';
// 2.客户列表
// $str = '{"table_type": "my"}';
// 3.领取客户
// $str = '{"id": 4,"campus_id": 1}';
// 4.新增客户/编辑客户/查询客户资料
// $str = '{
// 	"ctype": 1,
// 	"campus_id": 1,
// 	"student_name": "wf",
// 	"phone": "13969066090",
// 	"sex": 1,
// 	"channel": 1,
// 	"intentional_grade": 1,
// 	"user_id": 1,
// 	"guardian": "wf",
// 	"guardian_phone": "13969066090",
// 	"school_class": "wfwfwfwf",
// 	"grade": 1,
// 	"address": "wf111111",
// 	"weixin": "wf111",
// 	"remark": "11111111"
// }';
// 5.客户详情、客户跟进记录
// $str = '{"id": 23,"user_id": 100,"campus_id": 1}';
// $str = '{"campus_id":1,"nonceStr":"5d197c8f4f6ee","sign":"A1C17C8FDF40D22C4DFA0DA482A4D28C"}';
$str = '{"name":"篮球","type":0,"campus_id":1,"nonceStr":"5d197c8f4f6ee","sign":"A1C17C8FDF40D22C4DFA0DA482A4D28C"}';
$signData = json_decode($str,true);
$signData['nonceStr'] = uniqid();

/*$data = [
    'robot_id' => 'hsr000003',
    'user_id' => 'orwGP4gnQlIgmwhoRgDVpD0X8ZHY',
    'door_id' => 'door01',
    'open_time' => '2018-12-05 12:45:20',
    'close_time' => '2018-12-05 12:45:32',
    'nonceStr' => '15623896577'
];
*/
$data = array_change_key_case($signData);
ksort($data);
foreach ($data as $key=>&$val) {
 if($key=='sign'){
     unset($data[$key]);
     continue;
    }
    if (is_array($val)) {
        $val = json_encode($val,JSON_UNESCAPED_UNICODE);
    }
}
$_data = _buildQuery($data);

//接口签名
$sign = strtoupper(md5($_data.'&key=mM4NTUxZDMzNTJhMDUxN2ZjZmZob2lob2kxMzY2QyZTZiZWY1ZWZjNIxNDI1NDMxMw'));

$signData['sign'] = $sign;
var_dump(
    'api接口签名'.$sign,
    '请求json：'.json_encode($signData),
    $_data.'&key=mM4NTUxZDMzNTJhMDUxN2ZjZmZob2lob2kxMzY2QyZTZiZWY1ZWZjNIxNDI1NDMxMw'
);